package com.cssy.xxkj.attach.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public class CommUtils {

	public static String saveUploadFile(String baseDir,MultipartFile f) {
		if (f == null)
			return null;
		// 每天一个目录，如果目录不存在，创建它
		try {
			String relativeFilePath = getNewFilePath(baseDir);
			File dest = new File(getAbsoluteFilePath(baseDir,relativeFilePath));
			FileUtils.copyInputStreamToFile(f.getInputStream(),dest);
			return relativeFilePath;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static String saveUploadFile(String baseDir,File f) {
		if (f == null)
			return null;
		// 每天一个目录，如果目录不存在，创建它
		try {
			String relativeFilePath = getNewFilePath(baseDir);
			File dest = new File(getAbsoluteFilePath(baseDir,relativeFilePath));
			if (!f.exists())
				f.createNewFile();
			FileUtils.copyFile(f, dest);
			return relativeFilePath;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}
	
	private static String getNewFilePath(String baseDir) throws IOException {
		Date date = new Date();
		String dir = new SimpleDateFormat("yyyy").format(date)+"/"
					+ new SimpleDateFormat("MM").format(date)+"/"
					+ new SimpleDateFormat("dd").format(date);
		
		File file = new File(baseDir+ "/" + dir);
		if (!file.exists()) {
			FileUtils.forceMkdir(file);
		}
		// 保存文件，并将文件相对路径保存在relativeFilePaths变量中
		String relativeFilePath = new StringBuilder(dir).append("/").append(UUID.randomUUID().toString())
				.toString();
		return relativeFilePath;
	}
	
	public static String getAbsoluteFilePath(String baseDir,String relativePath) {
		//防止删除整个目录
		if(StringUtils.isBlank(relativePath))
			throw new RuntimeException("can not retrieve file by NULL path");
		return baseDir + "/" + relativePath;
	}
	
	public static byte[] readFile(File f) throws IOException {
		ByteArrayOutputStream bout = null;
		InputStream in = null;
		try {
			bout = new ByteArrayOutputStream();
			in = new FileInputStream(f);
			byte[] buffer = new byte[1024 * 1024];
			int l = -1;
			while ((l = in.read(buffer)) != -1) {
				bout.write(buffer, 0, l);
				bout.flush();
			}
			bout.flush();
			return bout.toByteArray();
		} finally {
			bout.close();
			in.close();
		}
	}
	
	public static final List<String> splitIds(String paramStr){
		List<String> list = new ArrayList<String>();
		if(StringUtils.isNotBlank(paramStr)){
			String params[] = paramStr.split(",");
			for(String idStr : params){
				if(StringUtils.isNotBlank(idStr))
					list.add(idStr.trim());
			}
		}
		return list;
	}
}
